<template>
  <div class="distribution-distributors">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分销员管理</span>
          <el-button type="primary" @click="handleAdd">添加分销员</el-button>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="分销员姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入分销员姓名"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 分销员列表 -->
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="分销员" min-width="150">
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <el-avatar
                :size="40"
                :src="VITE_URL + '/storage/' + scope.row.avatar"
                style="margin-right: 10px;"
              />
              <div>
                <div>{{ scope.row.customer_name }}</div>
                <div style="font-size: 12px; color: #999;">{{ scope.row.telephone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.level === 1">一级</el-tag>
            <el-tag v-else type="success">二级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="累计佣金" width="120">
          <template #default="scope">
            ¥{{ scope.row.total_commission || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="可提现佣金" width="120">
          <template #default="scope">
            ¥{{ scope.row.withdrawable_commission || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        style="margin-top: 20px; text-align: right;"
      />

      <!-- 添加/编辑分销员对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
      >
        <el-form
          :model="dialogForm"
          :rules="dialogRules"
          ref="dialogFormRef"
          label-width="100px"
        >
          <el-form-item label="客户" prop="customer_id">
            <el-select
              v-model="dialogForm.customer_id"
              placeholder="请选择客户"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <div style="display: flex; justify-content: space-between;">
                  <span>{{ item.name }}</span>
                  <span style="color: #999;">{{ item.telephone }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="等级" prop="level">
            <el-select v-model="dialogForm.level" placeholder="请选择等级">
              <el-option label="一级分销员" :value="1" />
              <el-option label="二级分销员" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="dialogForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitDialogForm" :loading="dialogSaving">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const VITE_URL = (window as any).VITE_URL

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  name: '',
  status: ''
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogSaving = ref(false)
const dialogForm = ref({
  id: 0,
  customer_id: null,
  level: 1,
  status: 1
})
const dialogFormRef = ref()
const isEdit = ref(false)

// 表单验证规则
const dialogRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  level: [{ required: true, message: '请选择等级', trigger: 'change' }]
}

// 客户列表
const customerList = ref([])

// 获取分销员列表
const getDistributorList = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', currentPage.value.toString())
    params.append('limit', pageSize.value.toString())
    
    if (searchForm.value.name) {
      params.append('name', searchForm.value.name)
    }
    if (searchForm.value.status !== '') {
      params.append('status', searchForm.value.status)
    }
    
    const url = `${VITE_URL}/admin.distribution/distributor_list?${params.toString()}`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      tableData.value = res.data.data.list
      total.value = res.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取分销员列表失败')
  } finally {
    loading.value = false
  }
}

// 获取客户列表
const getCustomerList = async () => {
  try {
    const url = `${VITE_URL}/admin.customer/list`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      customerList.value = res.data.list
    }
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getDistributorList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    name: '',
    status: ''
  }
  currentPage.value = 1
  getDistributorList()
}

// 分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  getDistributorList()
}

// 添加分销员
const handleAdd = () => {
  dialogTitle.value = '添加分销员'
  isEdit.value = false
  dialogForm.value = {
    id: 0,
    customer_id: null,
    level: 1,
    status: 1
  }
  dialogVisible.value = true
}

// 编辑分销员
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑分销员'
  isEdit.value = true
  dialogForm.value = {
    id: row.id,
    customer_id: row.customer_id,
    level: row.level,
    status: row.status
  }
  dialogVisible.value = true
}

// 提交表单
const submitDialogForm = async () => {
  try {
    await dialogFormRef.value.validate()
    
    dialogSaving.value = true
    let url = ''
    let data = {}
    
    if (isEdit.value) {
      // 编辑
      url = `${VITE_URL}/admin.distribution/update_distributor`
      data = {
        id: dialogForm.value.id,
        level: dialogForm.value.level,
        status: dialogForm.value.status
      }
    } else {
      // 添加
      url = `${VITE_URL}/admin.distribution/add_distributor`
      data = {
        customer_id: dialogForm.value.customer_id,
        level: dialogForm.value.level,
        status: dialogForm.value.status
      }
    }
    
    const res = await axios.post(url, data)
    if (res.data.status === 0) {
      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
      dialogVisible.value = false
      getDistributorList()
    } else {
      ElMessage.error(res.data.message || (isEdit.value ? '编辑失败' : '添加失败'))
    }
  } catch (error) {
    ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
  } finally {
    dialogSaving.value = false
  }
}

// 删除分销员
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除分销员"${row.customer_name}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const url = `${VITE_URL}/admin.distribution/delete_distributor`
      const res = await axios.post(url, { id: row.id })
      if (res.data.status === 0) {
        ElMessage.success('删除成功')
        getDistributorList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 状态变更
const handleStatusChange = async (row: any) => {
  try {
    const url = `${VITE_URL}/admin.distribution/update_distributor`
    const data = {
      id: row.id,
      level: row.level,
      status: row.status
    }
    const res = await axios.post(url, data)
    if (res.data.status === 0) {
      ElMessage.success('状态更新成功')
    } else {
      ElMessage.error(res.data.message || '状态更新失败')
      // 恢复状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 恢复状态
    row.status = row.status === 1 ? 0 : 1
  }
}

onMounted(() => {
  getDistributorList()
  getCustomerList()
})
</script>

<style scoped>
.distribution-distributors {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>